#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>    /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>

/*

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

int pthread_join(pthread_t thread, void **retval);
void pthread_exit(void *retval);
*/

int g_val = 10;

void *start_routine1(void *sem)
{
    sem_wait(sem); // P
    g_val = 100;
    sleep(3);
    printf("start_routine1  %d\n", g_val);
    sem_post(sem); // V
}

void *start_routine2(void *sem)
{
    sleep(1);
    sem_wait(sem); // P
    g_val = 200;
    printf("start_routine2  %d\n", g_val);
    sem_post(sem); // V
}

int main()
{

    printf("main\n");

    // 创建一个信号量
    sem_t *sem;
    sem_init(sem, 0, 1);

    // 创建一个线程
    pthread_t thread1;
    pthread_create(&thread1, NULL, start_routine1, sem);

    pthread_t thread2;
    pthread_create(&thread2, NULL, start_routine2, sem);

    pause();

    return 0;
}
